package cn.puge.mertisfront.controller;

import cn.puge.commonutils.R;
import cn.puge.mertisfront.entity.PugeUser;
import cn.puge.mertisfront.entity.PugeUserLogin;
import cn.puge.mertisfront.entity.QqOpenid;
import cn.puge.mertisfront.service.PugeUserLoginService;
import cn.puge.mertisfront.service.PugeUserService;
import cn.puge.mertisfront.utils.ConstantPropertiesUtil;
import cn.puge.mertisfront.utils.HttpClientUtils;
import cn.puge.mertisfront.utils.QQHttpClient;
import cn.puge.servicebase.exceptionhandler.PuGeiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author LIJW
 * @date 2020/11/30 10:48
 */



@Controller
@CrossOrigin
@RequestMapping("/mertisfront/LoginQq")
public class pugeqqLogin {


    @Autowired
    private PugeUserService pugeUserService;



    @Autowired
    private PugeUserLoginService pugeUserLoginService;


    @GetMapping("puge")
    public String pugeLogin(){

        //QQ开放平台授权地址
     String baseUrl = "https://graph.qq.com/oauth2.0/authorize" +
             "?response_type=code" +
             "&client_id=%s" +
             "&redirect_uri=%s";
     //回调地址
        String qqOpenRedirectUrl = ConstantPropertiesUtil.QQ_OPEN_REDIRECT_URL;
        try {
            qqOpenRedirectUrl = URLEncoder.encode(qqOpenRedirectUrl,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new PuGeiException(20001, e.getMessage());
        }

        //生成qrcodeUrl
        String qrcodeUrl = String.format(
                baseUrl,
                ConstantPropertiesUtil.QQ_OPEN_APP_ID,
                qqOpenRedirectUrl
        );
        return "redirect:" + qrcodeUrl;
    }






    /**
     * 获取openid
     * @param code
     * @return
     */
    @GetMapping("qqpuge")
    public String qqpuge(@RequestParam("code") String code)  {

        String userAccessTokenUrl = "https://graph.qq.com/oauth2.0/token" +
                "?grant_type=authorization_code" +
                "&client_id=%s" +
                "&client_secret=%s" +
                "&code=%s" +
                "&redirect_uri=%s";

        //使用工具拼起请求地址，生成新字符串变量
        String accessTokenOpenid = String.format(
                userAccessTokenUrl,
                ConstantPropertiesUtil.QQ_OPEN_APP_ID,
                ConstantPropertiesUtil.QQ_OPEN_APP_KEY,
                code,
                ConstantPropertiesUtil.QQ_OPEN_REDIRECT_URL
        );

        //发送http请求，获取数据包含access_Token


        String accessToken = null;
        try {
            accessToken = QQHttpClient.getAccessToken(accessTokenOpenid);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(accessToken);


         String getOpenIdUrl = "https://graph.qq.com/oauth2.0/me" +
                 "?access_token="+accessToken;
        String openid= null;
        try {
            openid= QQHttpClient.getOpenID(getOpenIdUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }

        PugeUser userOpenid = getUserOpenid(openid);
        if (StringUtils.isEmpty(userOpenid)){
            return "redirect:"+ ConstantPropertiesUtil.Puge_OPEN_REDIRECT_URL+"?openid="+openid;
        }


        return "redirect:"+ ConstantPropertiesUtil.Puge_OPEN_REDIRECT_URL+"?token="+userOpenid.getId();
    }


    /**
     * 查询用户信息
     * @param openid
     * @return
     */
    public PugeUser getUserOpenid(String openid){
        QueryWrapper<PugeUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("qq_openid",openid);
        PugeUser user = pugeUserService.getOne(queryWrapper);
        return user;
    }


}
